import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/checkin/checkinmodel.dart';
import 'package:opene/ui/checkin/checkinverifypage.dart';
import 'package:opene/ui/returns/bounce/returnsbouncesubmitscreen.dart';
import 'package:opene/ui/returns/preprocess/preprocessscreen.dart';
import 'package:opene/ui/returns/returnsdialogscreen.dart';
import 'package:opene/ui/returns/returnsmodel.dart';
import 'package:opene/utils/ImageUtils.dart';
import 'package:toast/toast.dart';

class PreprocessReasonScreen extends StatelessWidget {
  PreprocessReasonQr bounceReasonQr;

  PreprocessReasonScreen({this.bounceReasonQr});

  @override
  Widget build(BuildContext context) {
    return PreprocessReasonPage(bounceReasonQr: bounceReasonQr);
  }
}

class PreprocessReasonPage extends StatefulWidget {
  PreprocessReasonQr bounceReasonQr;

  PreprocessReasonPage({this.bounceReasonQr});

  @override
  _PreprocessReasonPageState createState() => _PreprocessReasonPageState(bounceReasonQr: bounceReasonQr);
}

class _PreprocessReasonPageState extends BaseState<PreprocessReasonScreen> {
  PreprocessReasonQr bounceReasonQr;

  _PreprocessReasonPageState({this.bounceReasonQr});

  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();
  bool isDamage = false;
  PhotoBean bolPhoto, doorPhoto, sealPhoto, damagePhoto;

  int index = 0, position;

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Returns: Shipment";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      bolPhoto = new PhotoBean();
      doorPhoto = new PhotoBean();
      sealPhoto = new PhotoBean();
      damagePhoto = new PhotoBean();
    });
  }

  Future pickImages(context) async {
    File image = await ImageUtils.chosePhotoOnAlbumOrCamera(context: context);
    print(image.path);
    String name = "";
    setState(() {
      switch (index) {
        case 0:
          bolPhoto.image = image;
          name = "overall";
          break;
        case 1:
          doorPhoto.image = image;
          name = "trk";
          break;
        case 2:
          sealPhoto.image = image;
          name = "sku";
          break;
        case 3:
          damagePhoto.image = image;
          name = "damage";
          break;
      }
      fileUpload("Bounce", "Bounce", image, name, index, position, false, false);
      print("index:${index},position:${position}");
      print(image.path);
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                "Tracking NO#: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Text(
                Utils.getStringisEmpty(bounceReasonQr.tracking_number),
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
              ),
            ],
          ),
          Row(
            children: [
              Text(
                "SKU(QTY): ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Text(
                "${Utils.getStringisEmpty(bounceReasonQr.sku_barcode)}(${Utils.getStringisInteger(bounceReasonQr.quantity)})",
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
              ),
            ],
          ),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 1,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          setState(() {
                            isDamage = false;
                          });
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        "Good",
                        style: TextStyle(color: this.type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                      onTap: () {
                        setState(() {
                          isDamage = false;
                        });
                      },
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 2,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          setState(() {
                            isDamage = true;
                          });
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        "Damaged",
                        style: TextStyle(color: this.type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                      onTap: () {
                        setState(() {
                          isDamage = true;
                        });
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
          Expanded(
            flex: 1, //设置权重
            child: SingleChildScrollView(
              controller: controller, // 设置控制器
              child: Column(
                children: [
                  setPhotoView("Overall photo:  ", 0, bolPhoto),
                  setPhotoView("TRK# photo:  ", 1, doorPhoto),
                  setPhotoView("SKU photo:  ", 2, sealPhoto),
                  Visibility(
                    visible: isDamage,
                    child: setPhotoView("Damage(s):  ", 3, sealPhoto),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Container setPhotoView(String hintText, int type, PhotoBean photoBean) {
    return Container(
      height: 70,
      margin: const EdgeInsets.only(left: 0, top: 10, right: 0, bottom: 0),
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Expanded(
            flex: 1, //设置权重
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  '*',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                ),
                Text(
                  hintText,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                ),
              ],
            ),
          ),
          Expanded(
              flex: 2, //设置权重
              child: Row(
                children: [
                  Container(
                    width: 70,
                    height: 70,
                    child: Stack(
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            // 请求焦点
                            FocusScope.of(context).requestFocus(FocusNode());
                            index = type;
                            ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                          },
                          child: photoBean.image == null
                              ? (photoBean.urlImg == null
                                  ? Image.asset(
                                      'assets/images/add.png',
                                      width: 70,
                                      height: 70,
                                      fit: BoxFit.cover,
                                    )
                                  : Image.network(
                                      Constants.baseImgUrl + photoBean.urlImg,
                                      width: 70,
                                      height: 70,
                                      fit: BoxFit.cover,
                                    ))
                              : Image.file(
                                  photoBean.image,
                                  width: 70,
                                  height: 70,
                                  fit: BoxFit.cover,
                                ),
                        ),
                        Visibility(
                          visible: ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? false : true,
                          child: Positioned(
                            top: 2.0,
                            right: 2.0,
                            child: GestureDetector(
                              onTap: () {
                                setState(() {
                                  photoBean.urlImg = null;
                                  photoBean.image = null;
                                });
                              },
                              child: Image.asset(
                                'assets/images/ic_delete_menu.png',
                                width: 15,
                                height: 15,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    flex: 2, //设置权重
                    child: Text(
                      '',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                    ),
                  ),
                ],
              )),
        ],
      ),
    );
  }

  ListView setListView(int type, List<PhotoBean> data) {
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        PhotoBean photoBean = data[index];
        print(photoBean.toString());
        return Container(
          height: 70,
          width: 70,
          margin: const EdgeInsets.only(left: 0, top: 0, right: 10, bottom: 0),
          child: Stack(
            children: <Widget>[
              GestureDetector(
                onTap: () {
                  // 请求焦点
                  FocusScope.of(context).requestFocus(FocusNode());
                  this.index = type;
                  this.position = index;
                  ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                },
                child: photoBean.image == null
                    ? (photoBean.urlImg == null
                        ? Image.asset(
                            'assets/images/add.png',
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          )
                        : Image.network(
                            Constants.baseImgUrl + photoBean.urlImg,
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          ))
                    : Image.file(
                        photoBean.image,
                        width: 70,
                        height: 70,
                        fit: BoxFit.cover,
                      ),
              ),
              Visibility(
                visible: ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? false : true,
                child: Positioned(
                  top: 2.0,
                  left: 53,
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        data.removeAt(index);
                      });
                    },
                    child: Image.asset(
                      'assets/images/ic_delete_menu.png',
                      width: 15,
                      height: 15,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    switch (type) {
      case 0:
        bolPhoto.urlImg = path;
        break;
      case 1:
        doorPhoto.urlImg = path;
        break;
      case 2:
        sealPhoto.urlImg = path;
        break;
      case 3:
        damagePhoto.urlImg = path;
        break;
    }

    if (isSubmit) {
      submitData();
    }
  }

  @override
  void setNext() {
    submitData();
  }

  void submitData() {
    ToastContext().init(context);

    if (bolPhoto.image == null) {
      Toast.show("Please add overall photo", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (doorPhoto.image == null) {
      Toast.show("Please add trk photo", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (sealPhoto.image == null) {
      Toast.show("Please add sku photo", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }

    if (type == 2 && damagePhoto.image == null) {
      Toast.show("Please add damage photo", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (Utils.isEmpty(bolPhoto.urlImg)) {
      fileUpload("Bounce", "Bounce", bolPhoto.image, "overall", 0, position, true, true);
      return;
    }
    if (Utils.isEmpty(doorPhoto.urlImg)) {
      fileUpload("Bounce", "Bounce", doorPhoto.image, "trk", 1, position, true, true);
      return;
    }
    if (Utils.isEmpty(sealPhoto.urlImg)) {
      fileUpload("Bounce", "Bounce", sealPhoto.image, "sku", 2, position, true, true);
      return;
    }
    if (Utils.isEmpty(damagePhoto.urlImg)) {
      fileUpload("Bounce", "Bounce", sealPhoto.image, "damage", 3, position, true, true);
      return;
    }

    bounceReasonQr.overall = bolPhoto.urlImg;
    bounceReasonQr.trkPhoto = doorPhoto.urlImg;
    bounceReasonQr.skuPhoto = sealPhoto.urlImg;
    bounceReasonQr.damaged = damagePhoto.urlImg;

    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => PreprocessScreen(bounceReasonQr: bounceReasonQr)),
    ).then((value) => {
          if (value != null && value) {Navigator.pop(context, true)}
        });
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      bolPhoto = new PhotoBean();
      doorPhoto = new PhotoBean();
      sealPhoto = new PhotoBean();
      damagePhoto = new PhotoBean();
    });
  }

  void checkSubmit(CheckinInfo checkinInfo, CheckinPendingQr checkinPendingQr) async {
    String json = jsonEncode(checkinPendingQr);
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.checkSubmit, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      CheckinPendingModel checkinPending = CheckinPendingModel.fromJson(baseResponse.data);
      if (checkinInfo.operationMethod == "container") {
        Navigator.pop(context, true);
      } else {
        Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => CheckinVerify(
                    data: checkinInfo,
                    checkinPending: checkinPending,
                  )),
        ).then((value) => {Navigator.pop(context, value)});
      }
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
}
